package com.shwread.android.ui.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;

import com.shwread.android.qysw10000227.R;
import com.shwread.android.ui.widget.citypicker.ScrollerNumberPicker;
import com.shwread.android.ui.widget.citypicker.ScrollerNumberPicker.OnSelectListener;

import java.util.HashMap;
import java.util.List;

import logic.bean.Area;
import logic.dao.AreaDao;


/**
 * 全国城市选择控件
 * @author 刘宾  
 * @date 2015年4月8日 下午8:39:29
 */
public class SelectCityDialog
        extends
        Dialog
{
	/** 刷新界面 */
	private static final int REFRESH_VIEW = 0x001;
	private static AreaDao                      dao;
	private static List<Area>                   provinces;
	private static HashMap<Integer, List<Area>> data;
	private Context                             context;
	private TextView                            tvFinish,tvCancel;
	private SelectCityListener                  listener;
	private Integer                             provincesId, cityId, areaId;
	private int                                 provincesIndex, cityIndex, areaIndex;
	private List<Area>                          citys, areas;
	/** 滑动控件 */
	private ScrollerNumberPicker provincePicker;
	private ScrollerNumberPicker cityPicker;
	private ScrollerNumberPicker areaPicker;
	/** 选择监听 */
	private OnSelectingListener onSelectingListener;
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case REFRESH_VIEW:
				if (onSelectingListener != null)
					onSelectingListener.selected(true);
				break;
			}
		}

	};
	public SelectCityDialog(Context cxt) {
		super(cxt, R.style.common_dialog);
		context = cxt;
		if (null == provinces || null == data) initData(context);
	}
	public SelectCityDialog(Context cxt,int provincesId,int cityId,int areaId) {
		super(cxt, R.style.common_dialog);
		this.context = cxt;
		this.provincesId = provincesId;
		this.cityId = cityId;
		this.areaId = areaId;
		if (null == provinces || null == data) initData(context);
	}
	
	@SuppressLint ("UseSparseArrays")
	public static void initData(Context context) {
		if(null==dao) dao = AreaDao.getInstance(context);
		if(null==provinces) provinces = dao.query(1);
//		Logger.e("添加省级数据：" + provinces.size());
		
		if(null!=data) return;
		data = new HashMap<Integer, List<Area>>();
		for (Area area : provinces)
		{
			final List<Area> curr = dao.query(area.id);
			data.put(area.id, curr);
//			Logger.e("添加市级数据：" + curr.size() + " - " + area.toString());
		}
		final List<Area> cityList = dao.queryByType(2);
		for (Area area : cityList)
		{
			final List<Area> curr = dao.query(area.id);
			data.put(area.id, curr);
//			Logger.e("添加区县级数据：" + curr.size() + " - " + area.toString());
		}
	}

	public void setListener(SelectCityListener listener){
		this.listener = listener;
	}

	public boolean hasData(){
		return !(null==provinces || provinces.isEmpty() || provinces.size()<=0 || null==data || data.isEmpty() || data.size()<=0);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setCancelable(false);
		findViews();
		getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		getWindow().setGravity(Gravity.BOTTOM);
	}
	
	private void findViews() {
		View view = LayoutInflater.from(context).inflate(R.layout.select_city, null);
		provincePicker = (ScrollerNumberPicker) view.findViewById(R.id.city_picker_province);
		cityPicker = (ScrollerNumberPicker) view.findViewById(R.id.city_picker_city);
		areaPicker = (ScrollerNumberPicker) view.findViewById(R.id.city_picker_area);
		tvFinish = (TextView) view.findViewById(R.id.select_city_finish);
		tvCancel = (TextView) view.findViewById(R.id.select_city_cancel);
		setContentView(view);

		provincePicker.setData(provinces);
		citys = data.get(provinces.get(0).id);
		cityPicker.setData(citys);
		areas = data.get(citys.get(0).id);
		areaPicker.setData(areas);
		citys = data.get(null==provincesId ? provinces.get(0).id : provincesId);
		cityPicker.setData(citys);
		areas = data.get(null==cityId ? citys.get(0).id : cityId);
		areaPicker.setData(areas);
		initIndex();
		provincePicker.setDefault(provincesIndex);
		cityPicker.setDefault(cityIndex);
		areaPicker.setDefault(areaIndex);

		provincePicker.setOnSelectListener(new OnSelectListener() {

			@Override
			public void endSelect(int id, String text) {
				if (TextUtils.isEmpty(text)) return;
				if (provincesIndex != id) {
					if(TextUtils.isEmpty(cityPicker.getSelectedText())) return;
					if(TextUtils.isEmpty(areaPicker.getSelectedText())) return;

					citys = data.get(provinces.get(id).id);
					cityPicker.setData(citys);
					cityIndex = 0;
					cityPicker.setDefault(cityIndex);

					areas = data.get(citys.get(0).id);
					areaPicker.setData(areas);
					areaIndex = 0;
					areaPicker.setDefault(areaIndex);
					final int size = provincePicker.getListSize();
					if (id > size) {
						provincePicker.setDefault(size - 1);
					}
				}
				provincesIndex = id;
				Message message = new Message();
				message.what = REFRESH_VIEW;
				handler.sendMessage(message);
			}

			@Override
			public void selecting(int id, String text) { }
		});
		cityPicker.setOnSelectListener(new OnSelectListener() {

			@Override
			public void endSelect(int id, String text) {
				if (TextUtils.isEmpty(text)) return;
				if (cityIndex != id) {
					if(TextUtils.isEmpty(provincePicker.getSelectedText())) return;
					if(TextUtils.isEmpty(areaPicker.getSelectedText())) return;

					areas = data.get(citys.get(id).id);
					areaPicker.setData(areas);
					areaIndex = 0;
					areaPicker.setDefault(areaIndex);
					final int size = cityPicker.getListSize();
					if (id > size) {
						cityPicker.setDefault(size - 1);
					}
				}
				cityIndex = id;
				Message message = new Message();
				message.what = REFRESH_VIEW;
				handler.sendMessage(message);
			}

			@Override
			public void selecting(int id, String text) { }
		});
		areaPicker.setOnSelectListener(new OnSelectListener() {

			@Override
			public void endSelect(int id, String text) {
				if (TextUtils.isEmpty(text)) return;
				if (areaIndex != id) {
					if(TextUtils.isEmpty(provincePicker.getSelectedText())) return;
					if(TextUtils.isEmpty(cityPicker.getSelectedText())) return;

					final int size = areaPicker.getListSize();
					if (id > size) {
						areaPicker.setDefault(size - 1);
					}
				}
				areaIndex = id;
				Message message = new Message();
				message.what = REFRESH_VIEW;
				handler.sendMessage(message);
			}

			@Override
			public void selecting(int id, String text) { }
		});
		tvFinish.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) {
				if(null != listener){
					listener.finish(provinces.get(provincesIndex),
					                citys.get(cityIndex),
					                null==areas?null:areas.get(areaIndex));
				}
				dismiss();
			}
		});
		tvCancel.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) {
				dismiss();
			}
		});
	}
	
	private void initIndex() {
	    if(null==provincesId || null==cityId || null==areaId) return;
	    if(null!=provinces){
	    	for (int i = 0; i < provinces.size(); i++)
	    	{
	    		if(provinces.get(i).id == provincesId){
	    			provincesIndex = i;
	    			break;
	    		}
	    	}
	    }
	    if(null!=citys){
	    	for (int i = 0; i < citys.size(); i++)
	    	{
	    		if(citys.get(i).id == cityId){
	    			cityIndex = i;
	    			break;
	    		}
	    	}
	    }
	    if(null!=areas){
	    	for (int i = 0; i < areas.size(); i++)
	    	{
	    		if(areas.get(i).id == areaId){
	    			areaIndex = i;
	    			break;
	    		}
	    	}
	    }
    }
	
	@Override
	public void dismiss() {
	    super.dismiss();

	    provincesId = null;
	    cityId = null;
	    areaId = null;
	}

	public void setOnSelectingListener(OnSelectingListener onSelectingListener) {
		this.onSelectingListener = onSelectingListener;
	}

	public interface OnSelectingListener {

		public void selected(boolean selected);
	}
}
